import { Message } from 'element-ui'
import axios from './axios'
import qs from 'qs' // 序列化时候用到
const request = {
    // get方式
    async get (url, params) {
        let { data: { success, data, errorMessage } } = await axios.get(url, { params: params })
        return new Promise((resolve, reject) => {
            if (success) {
                resolve(data)
            } else {
                Message.error(errorMessage)
                reject(data)
            }
        })
    },
    // post方式 + 序列化格式
    async formData (url, params) {
        let { data: { success, data, errorMessage } } = await axios.post(url, qs.stringify(params))
        return new Promise((resolve, reject) => {
            if (success) {
                resolve(data)
            } else {
                Message.error(errorMessage)
                reject(data)
            }
        })
    },
    // post方式
    async post (url, params) {
        let { data: { success, data, errorMessage } } = await axios.post(url, params)
        return new Promise((resolve, reject) => {
            if (success) {
                resolve(data)
            } else {
                Message.error(errorMessage)
                reject(data)
            }
        })
    },
    // 表格文件下载
    async download (url, params) {
        let { data: { success, data, errorMessage } } = await axios({
            method: 'post',
            url,
            data: params,
            responseType: 'blob',
            headers: {
                'Content-Type': 'application/octet-stream',
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        return new Promise((resolve, reject) => {
            if (success) {
                let fileName = data.headers['content-disposition'].split('filename=')[1]
                fileName = decodeURI(fileName)
                params.success(data.data)
                let blob = new Blob([data.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
                if ('download' in document.createElement('a')) {
                    const elink = document.createElement('a')
                    const href = URL.createObjectURL(blob)
                    elink.download = fileName
                    elink.style.display = 'none'
                    elink.href = href
                    document.body.appendChild(elink)
                    elink.click()
                    URL.revokeObjectURL(href)
                    document.body.removeChild(elink)
                } else { // IE10+下载
                    navigator.msSaveBlob(blob, fileName)
                }
                resolve()
            } else {
                Message.error(errorMessage)
                reject(data)
            }
        })
    }
}
export default request
